2023/12/231099字符

类型演算

typeof

const a: string = 'hello';
const b: typeof a = 'word';  // 根据 a 的类型推导 b 的类型
const User {
    name: string
    pass: string
}

function createUser(Cls: typeof User): User {
    return new Cls()
}
const user = createUser(User);

keyof

interface User {
    name: string
    pass: string
}

function fn(obj: User, prop: keyof User) {
    console.log(obj[prop]);
}

in

type User = {
    [prop in 'name' | 'pass']: string
}
const u = {
    name: 'bozai'
}

in keyof

interface User {
    name: string
    pass: string
}
type Obj = {
    // 将属性全部设为只读
    readonly [prop in keyof User]: User[prop]
}

const u: Obj = {
    name: 'bozai'
}

u.name = 'hhhh';  // 属性为只读,改不了

结合泛型

interface User {
    name: string
    pass: string
}
interface Artice {
    title: string
    content: string
}
type Partial<T> = {
    [prop in keyof T]?: T[prop]
}

const u: Partial<User> = {
    name: 'bozai'
}